<template>
  <div id="s">
    <!--  分隔-->
    <el-row>
      <el-col :span="24">
        <div class="grid-content bg-purple-light">
          <div style="float: right; margin-top: 2px;margin-right: 50px">
            <el-button size="info" @click="back" icon="el-icon-back" plain>返回</el-button>
            <el-button size="info" @click="save" :disabled="closeButton" plain>保存单据</el-button>
            <el-button size="info" @click="confirmStatement" :disabled="closeButton" plain>确认对账</el-button>
          </div>
          <div class="separate">&nbsp;&nbsp;&nbsp;&nbsp;<i class="el-icon-s-data"></i>基本信息</div>
        </div>
      </el-col>
    </el-row>
    <!--  查询条件-->

    <el-form :inline="true" :model="statement" :rules="rules" ref="ruleForm"
             label-width="150px" :label-position="'right'" style="text-align: left">
      <el-row type="flex" class="row-bg">
        <el-col :span="8">
          <el-form-item label="对账单号">
            <el-input v-model="statement.statementId" readonly clearable></el-input>
          </el-form-item>
          <el-form-item label="币种" prop="currency">
            <el-select v-model="statement.currency" clearable placeholder="请选择">
              <el-option value='人民币'></el-option>
              <el-option value='美元'></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="录入人员">
            <el-input v-model="statement.createUser" placeholder="录入人员" readonly clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="委托客户" prop="client">
            <el-input v-model="statement.client" placeholder="委托客户" suffix-icon="el-icon-search"
                      @click.native="showClients()" readonly></el-input>
          </el-form-item>
          <el-form-item label="税率%" prop="tax">
            <el-input v-model="statement.tax" placeholder="税率" clearable></el-input>
          </el-form-item>
          <el-form-item label="录入时间">
            <el-input v-model="statement.createTime" placeholder="录入人员" readonly clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="含税总额(元)" prop="total">
            <el-input v-model="statement.total" placeholder="含税总额" readonly clearable></el-input>
          </el-form-item>
          <el-form-item label="已收金额(元)">
            <el-input v-model="statement.checkedMoney" placeholder="已收金额" readonly clearable></el-input>
          </el-form-item>
          <el-form-item label="未收金额(元)">
            <el-input v-model="restMoney" placeholder="未收金额" readonly clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否开票" prop="checkedInvoice">
            <el-select v-model="statement.checkedInvoice" clearable placeholder="请选择">
              <el-option value='是'></el-option>
              <el-option value='否'></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发票号">
            <el-input v-model="statement.invoiceId" :readonly="statement.checkedInvoice=='否'" clearable></el-input>
          </el-form-item>
          <el-form-item label="对账日期">
            <el-input v-model="statement.checkedTime" placeholder="对账日期" readonly></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!--  客户查询-->
    <el-dialog
      title="客户"
      :visible.sync="showClient"
      width="50%">
      <div slot="footer" class="dialog-footer">
        <!--  查询条件-->
        <el-form :inline="true" :model="queryClient" style="text-align: left">
          <el-form-item label="客户编号">
            <el-input v-model="queryClient.customerId" placeholder="" clearable></el-input>
          </el-form-item>
          <el-form-item label="客户名称">
            <el-input v-model="queryClient.customerName" placeholder="" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getClient">查询</el-button>
          </el-form-item>
        </el-form>
        <!--  数据表格-->
        <el-table :data="clients" style="width: 100%" :border="true" highlight-current-row
                  @current-change="handleCurrentChange" :header-cell-style="{background:'#f7f7f7', color:'#666666'}">
          <el-table-column
            type="index"
            label="序号"
            width="50">
          </el-table-column>
          <el-table-column
            prop="customerId"
            label="客户编号"
            width="200">
          </el-table-column>
          <el-table-column
            prop="customerName"
            label="客户公司全称">
          </el-table-column>
        </el-table>
        <!--  分页-->
        <div style="width: 65%;">
          <el-pagination
            @size-change="getClient"
            @current-change="getClient"
            :current-page.sync="queryClient.pageNum"
            :page-sizes="[10, 20, 30, 40, 60, 80, 100]"
            :page-size.sync="queryClient.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="clientTotal">
          </el-pagination>
        </div>
        <el-button @click="cancle">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>
    <!--  分隔-->
    <el-row>
      <el-col :span="24">
        <div class="grid-content bg-purple-light">
          <div style="float: right; margin-top: 2px;margin-right: 50px">
            <el-button size="info" @click="receiveMoney" plain>应收订单</el-button>
          </div>
          <div class="separate">&nbsp;&nbsp;&nbsp;&nbsp;<i class="el-icon-s-grid"></i>应收订单</div>
        </div>
      </el-col>
    </el-row>
    <!--  订单表格-->
    <el-table :data="statement.relationOrders" show-summary :summary-method="getSummaries"
              :header-cell-style="{background:'#f7f7f7', color:'#666666'}">
      <el-table-column
        type="index"
        label="序号">
      </el-table-column>
      <el-table-column
        prop="orderId"
        label="委托单编号">
      </el-table-column>
      <el-table-column
        prop="customer.customerName"
        label="委托客户">
      </el-table-column>
      <el-table-column
        prop="orderFee"
        label="订单金额(元)">
      </el-table-column>
      <el-table-column
        prop="transportType"
        label="订单类型">
      </el-table-column>
      <el-table-column
        prop="currentStatus"
        label="订单状态">
      </el-table-column>
      <el-table-column
        prop="currentStatusTime"
        label="完成时间">
      </el-table-column>
      <el-table-column
        label="操作">
        <template v-slot="scope">
          <el-popconfirm title="确定删除吗？" @confirm="remove(scope.row)">
            <el-button slot="reference" type="text" size="small">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--  订单查询-->
    <el-dialog
      title="订单"
      :visible.sync="showOrder"
      width="50%">
      <div slot="footer" class="dialog-footer">
        <!--  查询条件-->
        <el-form :inline="true" :model="queryOrder" style="text-align: left">
          <el-form-item label="委托单号">
            <el-input v-model="queryOrder.orderId" placeholder="委托单号" clearable></el-input>
          </el-form-item>
          <el-form-item label="委托客户">
            <el-input v-model="statement.client" readonly></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getList">查询</el-button>
          </el-form-item>
        </el-form>
        <!--  表格-->
        <el-table :data="orders" :header-cell-style="{background:'#f7f7f7', color:'#666666'}"
                  ref="multipleTable" @selection-change="handleSelectionChange">
          <el-table-column
            type="selection"
            width="55">
          </el-table-column>
          <el-table-column
            type="index"
            label="序号">
          </el-table-column>
          <el-table-column
            prop="orderId"
            label="委托单编号">
          </el-table-column>
          <el-table-column
            prop="customer.customerName"
            label="委托客户">
          </el-table-column>
          <el-table-column
            prop="orderFee"
            label="订单金额(元)">
          </el-table-column>
          <el-table-column
            prop="transportType"
            label="订单类型">
          </el-table-column>
          <el-table-column
            prop="currentStatus"
            label="订单状态">
          </el-table-column>
          <el-table-column
            prop="currentStatusTime"
            label="完成时间">
          </el-table-column>
        </el-table>
        <!--  分页-->
        <div style="width: 65%;">
          <el-pagination
            @size-change="getList"
            @current-change="getList"
            :current-page.sync="queryOrder.pageNum"
            :page-sizes="[10, 20, 30, 40, 60, 80, 100]"
            :page-size.sync="queryOrder.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="orderTotal">
          </el-pagination>
        </div>
        <el-button @click="cancleOrder">取 消</el-button>
        <el-button type="primary" @click="confirmOrder">确 定</el-button>
      </div>
    </el-dialog>
    <!--  分隔-->
    <el-row>
      <el-col :span="24">
        <div class="grid-content bg-purple-light">
          <div style="float: right; margin-top: 2px;margin-right: 50px">
            <el-button size="info" @click="addIncome" plain>添加收款</el-button>
          </div>
          <div class="separate">&nbsp;&nbsp;&nbsp;&nbsp;<i class="el-icon-s-grid"></i>收款记录</div>

        </div>
      </el-col>
    </el-row>
    <!--  收款表格-->
    <el-table :data="statement.incomes" stripe show-summary :summary-method="getSummaries" highlight-current-row
              :header-cell-style="{background:'#f7f7f7', color:'#666666'}">
      <el-table-column
        type="index"
        label="序号">
      </el-table-column>
      <el-table-column
        prop="incomeId"
        label="交易号">
      </el-table-column>
      <el-table-column
        prop="incomeTime"
        label="交易时间">
      </el-table-column>
      <el-table-column
        prop="amount"
        label="收款金额(元)">
      </el-table-column>
      <el-table-column
        prop="type"
        label="交易方式">
      </el-table-column>
      <el-table-column
        prop="bank"
        label="银行名称">
      </el-table-column>
      <el-table-column
        prop="account"
        label="银行账户">
      </el-table-column>
      <el-table-column
        label="操作">
        <template v-slot="scope">
          <el-popconfirm title="确定删除吗？" @confirm="removeIncome(scope.row)">
            <el-button slot="reference" type="text" size="small">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--  添加收款-->
    <el-dialog
      title="收款"
      :visible.sync="showIncome"
      width="40%">
      <div slot="footer" class="dialog-footer">
        <!--  交易-->
        <el-form :model="income" style="text-align: left; width: 80%" label-width="120px" label-position="right"
                 ref="paymentRule" :rules="paymentRules">
          <el-form-item label="交易号" prop="incomeId">
            <el-input v-model="income.incomeId" placeholder="交易号" clearable></el-input>
          </el-form-item>
          <el-form-item label="收款金额(元)" prop="amount">
            <el-input v-model="income.amount" placeholder="收款金额" clearable></el-input>
          </el-form-item>
          <el-form-item label="收款时间" style="width: 100%" prop="incomeTime">
            <el-date-picker
              v-model="income.incomeTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="收款方式" prop="type">
            <el-select v-model="income.type" clearable placeholder="请选择">
              <el-option value='银行转账'></el-option>
              <el-option value='支付宝'></el-option>
              <el-option value='微信'></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="银行名称">
            <el-input v-model="income.bank" placeholder="银行名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="对方账号">
            <el-input v-model="income.account" placeholder="对方账号" clearable></el-input>
          </el-form-item>
        </el-form>
        <el-button @click="cancleIncome">取 消</el-button>
        <el-button type="primary" @click="confirmIncome">确 定</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
export default {
  name: "AddStatement",
  data() {
    return {
      //对账单参数
      statement: {
        total: 0,
        checkedMoney: 0,
        checked: '否',
        checkedInvoice: '否',
        relationOrders: [],
        incomes: [],
        currency: '人民币',
        client: '',
        customerId: '',
        tax: 6
      },
      rules: {
        client: [{required: true, message: '请选择委托客户', trigger: 'blur'}],
        tax: [{required: true, message: '请输入税率', trigger: 'blur'}],
        checkedInvoice: [{required: true, message: '请选择是否开票，开票则输入发票号', trigger: 'change'}],
        total: [{required: true, message: '请选择关联订单', trigger: 'blur'}],
      },
      paymentRules: {
        incomeId: [{required: true, message: '请输入交易号', trigger: 'blur'}],
        amount: [{required: true, message: '请输入交易金额', trigger: 'blur'}],
        incomeTime: [{required: true, message: '请输入交易时间', trigger: 'change'}],
        type: [{required: true, message: '请选择交易类型', trigger: 'change'}]
      },
      //查询客户参数
      queryClient: {},
      clients: [],
      clientTotal: 0,
      selectClient: {},
      showClient: false,
      //订单参数
      orders: [],
      orderTotal: 0,
      showOrder: false,
      queryOrder: {
        pageNum: 1,
        pageSize: 10,
        orderId: '',
        orderCustomerId: ''
      },
      temRelaOrders: [],
      showIncome: false,
      income: {},
      //防止重复提交
      closeButton: false
    }
  },
  methods: {
    //确认对账请求
    confirmStatement() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          //判断是否总金额是否小于应收金额，否则禁止提交
          if (this.statement.total > this.statement.checkedMoney) {
            this.$message.error("实际收款金额小于应收总金额，不可对账")
          } else {
            this.$confirm('此操作将归档对账单,无法取消, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.statement.checked = '是';
              this.$axios({
                url: 'finance/statement/confirm',
                method: 'post',
                data: this.statement
              }).then(res => {
                if (res.data.success) {
                  this.closeButton = true;
                  this.$message.success(res.data.message);
                } else {
                  this.$message.error(res.data.message)
                }
              }).catch(err => {
                this.$message.error(err.message);
              })
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消'
              });
            });
          }
        }
      })
    },
    //保存对账单请求
    save() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.$axios({
            url: 'finance/statement/add',
            method: 'post',
            data: this.statement
          }).then(res => {
            if (res.data.success) {
              this.$message.success(res.data.message);
            } else {
              this.$message.error(res.data.message)
            }
          }).catch(err => {
            this.$message.error(err.message);
          })
        }
      })
    },
    //显示客户查询界面
    showClients() {
      this.showClient = true;
      this.getClient();
    },
    //查询客户请求
    getClient() {
      this.$axios({
        url: 'base/customer/getList',
        method: 'post',
        data: this.queryClient
      }).then(res => {
        if (res.data.success) {
          this.clients = res.data.object.list;
          this.clientTotal = res.data.object.total;
        } else {
          this.$message.error(res.data.message)
        }
      }).catch(err => {
        this.$message.error(err.message);
      })
    },
    //取到选定的客户
    handleCurrentChange(val) {
      this.selectClient = val;
    },
    //选定的客户赋给查询条件
    confirm() {
      if (this.selectClient != null) {
        this.statement.relationOrders = []
        this.statement.client = this.selectClient.customerName;
        this.statement.customerId = this.selectClient.customerId;
        this.queryOrder.orderCustomerId = this.selectClient.customerId;
      }
      this.showClient = false;
      this.$refs['ruleForm'].clearValidate('client')
    },
    //清空查询条件，关闭对话框
    cancle() {
      this.statement.client = '';
      this.showClient = false;
    },
    //订单相关操作
    getList() {
      this.$axios({
        url: 'order/form/getByCustomer',
        method: 'post',
        data: this.queryOrder
      }).then(res => {
        if (res.data.success) {
          this.orders = res.data.object.list;
          this.ordertotal = res.data.object.total;
        } else {
          this.$message.error(res.data.message)
        }
      }).catch(err => {
        this.$message.error(err.message);
      })
    },
    //显示订单窗口，如未选择客户提示选择客户
    receiveMoney() {
      if (this.statement.client != undefined) {
        this.temRelaOrders = [];
        this.$refs.multipleTable.clearSelection();
        this.showOrder = true;
        this.getList();
      } else {
        this.$message.info("请选择委托客户")
      }
    },
    //关闭订单窗口，清空已选择
    cancleOrder() {
      this.temRelaOrders = [];
      this.showOrder = false;
    },
    //确定选择订单。判断是否存在重复提交
    confirmOrder() {
      if (this.statement.relationOrders == undefined) {
        this.statement.relationOrders = []
      }
      for (let order of this.temRelaOrders) {
        for (let relaOrder of this.statement.relationOrders) {
          if (order.orderId == relaOrder.orderId) {
            this.$message.info('委托单重复，添加失败')
            return
          }
        }
        this.statement.relationOrders.push(order);
      }
      this.showOrder = false;
    },
    //选定的值存入中间参数
    handleSelectionChange(val) {
      this.temRelaOrders = val;
    },
    //删除订单
    remove(row) {
      this.statement.relationOrders.splice(this.statement.relationOrders.indexOf(row), 1)
      if (this.statement.relationOrders.length == 0) {
        this.statement.total = 0;
      }
    },
    //返回上一层
    back() {
      this.$router.back();
    },
    //打开交易记录窗口
    addIncome() {
      this.income = {}
      this.showIncome = true;
      this.$nextTick(() => {
        this.$refs['paymentRule'].clearValidate();
      })
    },
    //关闭交易记录窗口
    cancleIncome() {
      this.showIncome = false;
    },
    //确认交易记录添加，判断交易号是否重复
    confirmIncome() {
      if (this.statement.incomes == undefined) {
        this.statement.incomes = []
      }
      this.$refs['paymentRule'].validate((valid) => {
        if (valid) {
          for (let val of this.statement.incomes) {
            if (val.incomeId == this.income.incomeId) {
              this.$message.info("交易号重复，请重新输入")
              return
            }
          }
          this.statement.incomes.push(this.income);
          this.showIncome = false;
        }
      })
    },
    //删除交易
    removeIncome(row) {
      this.statement.incomes.splice(this.statement.incomes.indexOf(row), 1)
      if (this.statement.incomes.length == 0) {
        this.statement.checkedMoney = 0;
      }
    },
    //表格合计行计算规则，计算值赋给表单
    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总价';
          return;
        } else if (index != 3) {
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              if (column.property == 'orderFee') {
                this.statement.total = prev + curr;
              } else if (column.property == 'amount') {
                this.statement.checkedMoney = prev + curr;
              }
              return prev + curr;
            } else {
              if (column.property == 'orderFee') {
                this.statement.total = prev;
              } else if (column.property == 'amount') {
                this.statement.checkedMoney = prev;
              }
              return prev;
            }
          }, 0);
        } else {
        }
      });
      return sums;
    }
  },
  computed: {
    //计算剩余应收金额
    restMoney() {
      return this.statement.total - this.statement.checkedMoney;
    }
  },
  created() {
    //生成订单号录入人员录入时间
    this.statement.statementId = 'dz' + new Date().getTime()
    this.statement.createTime = new Date().getFullYear() + '-' + (new Date().getMonth() + 1) + '-' + new Date().getDate()
    this.statement.createUser = this.$store.state.loginUserName
    //查看对象赋给表单
    if (Object.getOwnPropertyNames(this.$route.params).length != 0) {
      this.statement = this.$route.params
      this.queryOrder.orderCustomerId = this.statement.customerId
    }

  }
}
</script>

<style scoped>

.bg-purple-light {
  background: rgb(237, 237, 237);
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
  margin-bottom: 15px;
}

/deep/ .el-table .el-table__body td .cell:empty::after,
.el-table .el-table__body td .cell > span:empty::after,
.el-table .el-table__body td .cell .approval:empty::after,
.el-table .el-table__body td .cell div:empty::after,
.el-table .el-table__body td .cell .line-limit-length:empty::after {
  content: "--";
}

#s {
  width: 90%;
  margin: 10px auto;
  background-color: #ffffff;
  box-shadow: 10px 10px 5px #c4c6c7;
  border-radius: 5px
}

.el-button--info:hover {
  background: #209e91;
  border-color: #209e91;
  color: #FFF;
}

.separate {
  width: 100%;
  height: 50px;
  background: #339999;
  border-color: #339999;
  text-align: left;
  line-height: 50px;
  color: #FFFFFF;
}
</style>
<style>
.el-table .warning-row {
  background: oldlace !important;
}

.el-table__body tr.current-row > td {
  background-color: rgba(65, 225, 105, 0.45) !important;
}
</style>
